import serial
import time
import binascii

UART_BAUD = 9600
UART_BYTESIZE = 8
UART_STOPBITS = 1
UART_PARITY = 'N'
TIMEOUT = 10

class KA3005P:
    def __init__(self, com_id):
        try:
            self.ser = serial.Serial(com_id, UART_BAUD, UART_BYTESIZE, UART_PARITY, UART_STOPBITS)
            print("串口打开成功")
        except:
            print("串口打开失败")
            while True:
                pass
            
    def read_data(self):
        data = ''
        while True:
            # ch = self.ser.read(self.ser.inWaiting())
            ch = self.ser.read(size=1)
            if ch == b'\n':
                break
            data += ch.decode('utf8')
        return data

    def read_id(self):
        self.ser.write('*IDN?\n'.encode("utf8"))
        id = self.read_data()
        return id

    def turn_on_beep(self):
        self.ser.write('BEEP1\n'.encode('utf8'))

    def turn_off_beep(self):
        self.ser.write('BEEP0\n'.encode('utf8'))

    def turn_on_output(self):
        self.ser.write('OUT1\n'.encode('utf8'))

    def turn_off_output(self):
        self.ser.write('OUT0\n'.encode('utf8'))

    def turn_on_ovp(self):
        self.ser.write('OVP1\n'.encode('utf8'))

    def turn_off_ovp(self):
        self.ser.write('OVP0\n'.encode('utf8'))

    def turn_on_ocp(self):
        self.ser.write('OCP1\n'.encode('utf8'))

    def turn_off_ocp(self):
        self.ser.write('OCP0\n'.encode('utf8'))

    def set_iset_current(self, channel, current):
        cmd = 'ISET%s:%s\n' % (channel, current)
        self.ser.write(cmd.encode('utf8'))

    def get_iset_current(self, channel):
        cmd = 'ISET%s?\n' % channel
        self.ser.write(cmd.encode('utf8'))
        current = self.read_data()
        return current
    
    def set_vset_voltage(self, channel, voltage):
        cmd = 'VSET%s:%s\n' % (channel, voltage)
        self.ser.write(cmd.encode('utf8'))

    def get_vset_voltage(self, channel):
        cmd = 'VSET%s?\n' % channel
        self.ser.write(cmd.encode('utf8'))
        voltage = self.read_data()
        return voltage
    
    def get_output_voltage(self, channel):
        cmd = 'VOUT%s?\n' % channel
        self.ser.write(cmd.encode('utf8'))
        time.sleep(0.1)
        voltage = self.read_data()
        return voltage

    def get_output_current(self, channel):
        cmd = 'IOUT%s?\n' % channel
        self.ser.write(cmd.encode('utf8'))
        time.sleep(0.1)
        current = self.read_data()
        return current
